package kk.learn.scala.work._5
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException
/**
 * <p>
 *
 * </p>
 *
 * @author KK
 * @since 2021-02-22
 */
object Worker{

  val client = new OkHttpClient

  def main(args: Array[String]): Unit = {
    // 注册
    val workerId:Int = (Math.random() * 10).toInt
    get(s"http://localhost:8080/register?workerId=$workerId")

    // 定时发送心跳
    while (true){
      Thread.sleep(5000L)
      get(s"http://localhost:8080/heartBeat?workerId=$workerId")
    }
  }

  // 一个http请求方法
  @throws[IOException]
  def get(url: String) = {
    val request = new Request.Builder().url(url).build
    try {
      val response = client.newCall(request).execute
      try response.body.string
      finally if (response != null) response.close()
    }
  }

}
